package MergeSorting;

/**
 * Created with IntelliJ IDEA.
 * Description:非递归归并排序算法
 * User: 均先生
 * Date: 2023-11-20
 * Time: 11:30
 */
public class MergeSortingNor {
    public static void mergeSort(int[] array) {
        int gap = 1;
        while (gap < array.length) {
            for (int i = 0; i < array.length; i = i+gap*2) {
                int left = i;
                int mid = left + gap - 1;
                int right = mid + gap;
                if (mid >= array.length) {
                    mid = array.length-1;
                }
                if (right >= array.length) {
                    right = array.length-1;
                }
                merge(array,left,mid,right);
            }
            gap *= 2;
        }
    }
    private static void merge(int[] array, int left, int mid, int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int[] tmpArr = new int[right-left+1];
        int k = 0;//tmpArr数组的下标
        while (s1 <= e1 && s2 <= e2) {//将分组数据排好序放入tmpArr
            if (array[s1] <= array[s2]) {
                tmpArr[k++] = array[s1++];
            }else {
                tmpArr[k++] = array[s2++];
            }
        }
        while (s1 <= e1) {
            tmpArr[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmpArr[k++] = array[s2++];
        }
        //将排好序的数组拷贝回原来的数组
        for (int i = 0; i < tmpArr.length; i++) {
            array[i+left] = tmpArr[i];
        }
    }
}
